<template>
  <div class="category-management">
    <!-- 筛选栏 -->
    <el-form :inline="true" :model="filters" class="filter-form">
      <el-form-item label="分类名称">
        <el-input v-model="filters.name" placeholder="请输入分类名称" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch" :loading="loading">搜索</el-button>
        <el-button @click="onReset">重置</el-button>
        <el-button type="success" @click="onCreate">新建分类</el-button>
      </el-form-item>
    </el-form>

    <!-- 分类表格 -->
    <el-table
      :data="filteredCategories"
      border
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="name" label="分类名称" min-width="200" />
      <el-table-column label="排序" width="80">
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="onEdit(row)">编辑</el-button>
          <el-button type="danger" size="small" @click="onDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        @current-change="onPageChange"
        @size-change="onSizeChange"
      />
    </div>

    <!-- 分类编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑分类' : '新建分类'"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit" :loading="submitLoading">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";

// 表单引用
const formRef = ref(null);

// 响应式数据
const loading = ref(false);
const submitLoading = ref(false);
const dialogVisible = ref(false);
const isEdit = ref(false);
const categories = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(20);

// 筛选条件
const filters = reactive({
  name: "",
});

// 表单数据
const form = reactive({
  _id: "",
  name: "",
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
};

// 获取分类列表
const fetchCategories = async () => {
  try {
    loading.value = true;
    const params = {
      keyword: filters.name
    };
    
    const response = await axios.get('http://localhost:3000/jjx/getClassifys', { params });
    
    if (response.data.code === 200) {
      categories.value = response.data.data || [];
      total.value = categories.value.length;
    } else {
      ElMessage.error(response.data.msg || '获取分类列表失败');
    }
  } catch (error) {
    console.error('获取分类列表失败:', error);
    ElMessage.error('获取分类列表失败');
  } finally {
    loading.value = false;
  }
};

// 过滤后的分类数据
const filteredCategories = computed(() => {
  return categories.value;
});

// 搜索
const onSearch = () => {
  currentPage.value = 1;
  fetchCategories();
};

// 重置
const onReset = () => {
  Object.assign(filters, {
    name: "",
  });
  currentPage.value = 1;
  fetchCategories();
};

// 分页变化
const onPageChange = (page) => {
  currentPage.value = page;
};

// 每页数量变化
const onSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
};



// 新建分类
const onCreate = () => {
  isEdit.value = false;
  resetForm(); // 重置表单数据
  dialogVisible.value = true;
};

// 编辑分类
const onEdit = (row) => {
  isEdit.value = true;
  Object.assign(form, row);
  dialogVisible.value = true;
};

// 删除分类
const onDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个分类吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    
    // 使用_id作为参数
    const response = await axios.delete(`http://localhost:3000/jjx/deleteClassify/${row._id}`);
    
    if (response.data.code === 200) {
      ElMessage.success('删除成功');
      fetchCategories();
    } else {
      ElMessage.error(response.data.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

// 提交表单
const onSubmit = async () => {
  try {
    // 验证表单
    await formRef.value.validate();
    
    submitLoading.value = true;
    
    if (isEdit.value) {
      // 更新分类 - 使用_id作为参数
      const response = await axios.put(`http://localhost:3000/jjx/updateClassify/${form._id}`, { name: form.name });
      if (response.data.code === 200) {
        ElMessage.success('分类更新成功');
        dialogVisible.value = false;
        fetchCategories();
      } else {
        ElMessage.error(response.data.msg || '分类更新失败');
      }
    } else {
      // 创建分类 - 只发送name字段
      const response = await axios.post('http://localhost:3000/jjx/addClassify', { name: form.name });
      if (response.data.code === 200) {
        ElMessage.success('分类创建成功');
        dialogVisible.value = false;
        fetchCategories();
      } else {
        ElMessage.error(response.data.msg || '分类创建失败');
      }
    }
  } catch (error) {
    if (error.name === 'ValidationError') {
      ElMessage.error('请填写完整的分类信息');
    } else {
      console.error('提交失败:', error);
      ElMessage.error('提交失败');
    }
  } finally {
    submitLoading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    _id: "",
    name: "",
  });
  // 清除表单验证状态
  if (formRef.value) {
    formRef.value.clearValidate();
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchCategories();
});
</script>

<style scoped>
.category-management {
  padding: 24px;
}
.filter-form {
  margin-bottom: 16px;
}
.pagination-wrapper {
  margin-top: 16px;
  text-align: right;
}
</style>